//
//  GHLocationManager.swift
//  GHSwiftProject
//
//  Created by Guanghui Liao on 4/14/18.
//  Copyright © 2018 liaoworking. All rights reserved.
//

import UIKit
import CoreLocation
///获取到经纬度的回调
typealias didLocatedCallback = ((Double,Double) -> (Void))
class GHLocationManager: NSObject {

    static let shared = GHLocationManager()
    //定位对象
    private var llocationManager:CLLocationManager?
    //获取到定位
    var didLocatedBlock: didLocatedCallback?
    
    
    override init() {
        super.init()
        
        llocationManager = CLLocationManager()
        llocationManager?.delegate = self
        llocationManager?.desiredAccuracy = kCLLocationAccuracyBestForNavigation
        llocationManager?.distanceFilter = 20
    }

    /// 开始定位
    ///
    /// - Parameter showAlert: 如果开启权限的话是否提示用户去开启权限,默认静默
    func startLocating(showAlert:Bool = false)-> GHLocationManager{
        switch CLLocationManager.authorizationStatus() {
            case .denied, .restricted:
                if showAlert {
                    UIAlertController.init(title: "提示", message: "未打开定位权限，请前往设置中进行开启", defaultActionButtonTitle: "确定", tintColor: UIColor.black).show()
                }
            case .notDetermined:
                llocationManager?.requestWhenInUseAuthorization()
            default :
                llocationManager?.startUpdatingLocation()
        }

        return self
    }
}


extension GHLocationManager: CLLocationManagerDelegate {
    
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        
        let location = locations.last
        
        if location?.coordinate.longitude != nil {
            print(location?.coordinate)
            if (self.didLocatedBlock != nil) {
                self.didLocatedBlock!(location!.coordinate.longitude, location!.coordinate.latitude)
            }
        }
        manager.stopUpdatingLocation()

    }
    
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
            print("定位失败\(error) code = 1")
    }
    
    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        if status == .authorizedWhenInUse || status == .authorizedAlways {
            self.startLocating()
        }
    }
    
}
